using System;
using System.Collections.Specialized;
using System.Web;
using System.Web.Security;
using System.Web.UI.Adapters;
using System.Web.UI.WebControls;
using Be.Timvw.Framework.Collections;
using System.Text.RegularExpressions;

namespace Be.Timvw.Framework.Web.UI.Adapters
{
    public class LoginAdapter : ControlAdapter
    {
        public static string ReturnUrlParameterName
        {
            get { return "returnUrl";  }
        }

        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);

            Login login = Control as Login;
            if (login == null) return;

            HttpContext httpContext = HttpContext.Current;
            if (httpContext == null) return;

            HttpRequest httpRequest = httpContext.Request;
            if (httpRequest == null) return;

            if (!string.Equals(httpRequest.HttpMethod, "GET", StringComparison.OrdinalIgnoreCase)) return;

            string path = httpRequest.Path;
            if (path == null) return;

            if (path != FormsAuthentication.LoginUrl) return;

            NameValueCollection queryString = httpRequest.QueryString;
            if (queryString == null) return;
            if (queryString.Count <= 0) return;

            string returnUrl = queryString[ReturnUrlParameterName];
            if (string.IsNullOrEmpty(returnUrl)) return;

            string clickedParameterName = LinkButtonAdapter.ClickedParameterName;
            if (!returnUrl.Contains(clickedParameterName)) return;

            HttpResponse httpResponse = httpContext.Response;
            if (httpResponse == null) return;

            NameValueCollection writableQuery = new NameValueCollection();
            foreach (string key in queryString.Keys)
            {
                writableQuery.Add(key, queryString[key]);
            }

            string returnUrlWithoutClickedParameter = Regex.Replace(returnUrl, string.Format(@"((\?|&){0}\=.*)$", clickedParameterName), string.Empty);
            writableQuery[ReturnUrlParameterName] = returnUrlWithoutClickedParameter;

            Uri loginUrlWithoutClickParameter = UriHelper.AddParameters(httpRequest.Url, writableQuery, DuplicateKeyBehavior.Replace);
            httpResponse.Redirect(loginUrlWithoutClickParameter.ToString(), false);
        }
    }
}
